#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "esp_console.h"
#include "argtable3/argtable3.h"
#include "cmd_decl.h"

#include "lwip/err.h"
#include "lwip/apps/sntp.h"

#define SNTP_SERVER "cn.ntp.org.cn"

static const char *TAG = "sntp";

//RTC_DATA_ATTR static int boot_count = 0;

static  uint8_t esp32_sntp_init =0;


void initialize_sntp(void){
    if(esp32_sntp_init ==0){
        ESP_LOGI(TAG, "正在初始化 SNTP");
        sntp_setoperatingmode(SNTP_OPMODE_POLL);
        sntp_setservername(0, SNTP_SERVER);
        sntp_init();
        esp32_sntp_init=1;
    }else{
        ESP_LOGI(TAG, "SNTP 初始化完成");
    }
}

//获得网络时间
void obtain_time(void){

    //在初始化nvs_flash和wifi后初始化sntp服务
    
    time_t now = 0;
    struct tm timeinfo = { 0 };
    initialize_sntp();

    // 等待时间的设定
    int retry = 0;
    const int retry_count = 10;

    setenv("TZ", "CST-8", 1);
    tzset();
    
    while(timeinfo.tm_year < (2016 - 1900) && ++retry < retry_count) {
        //ESP_LOGI(TAG, "等待系统时间设置… (%d/%d)", retry, retry_count);
        vTaskDelay(2000 / portTICK_PERIOD_MS);
        time(&now);
        localtime_r(&now, &timeinfo);
    }
    ESP_LOGI(TAG, "时间设定为 %s", asctime(&timeinfo));
    
    sntp_stop();
    esp32_sntp_init=0;
}


static int cmd_sntp(int argc, char** argv)
{
    //++boot_count;
    //ESP_LOGI(TAG, "启动计数: %d", boot_count);
    // Is time set? If not, tm_year will be (1970 - 1900).
    time_t now = 0;
    struct tm timeinfo = { 0 };
    time(&now);
    setenv("TZ", "CST-8", 1);
    tzset();
    localtime_r(&now, &timeinfo);
    
    if (timeinfo.tm_year < (2019 - 1900)) {
        ESP_LOGI(TAG, "时间还没有定下来。连接WiFi和获得时间超过NTP。");
        obtain_time();
        // 用当前时间更新'now'变量
        time(&now);
    }

    char strftime_buf[64];
   
    //setenv("TZ", "CST-8", 1);
    //tzset();
    //localtime_r(&now, &timeinfo);

    strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
    ESP_LOGI(TAG, "目前在上海的日期/时间是: %s", strftime_buf);
    ESP_LOGI(TAG, "tm:%4d-%02d-%02d 星期%d %02d:%02d:%02d\n",timeinfo.tm_year+1900,timeinfo.tm_mon+1,timeinfo.tm_mday,timeinfo.tm_wday,timeinfo.tm_hour,timeinfo.tm_min,timeinfo.tm_sec);
    return  0;
}


void register_sntp(){
    const esp_console_cmd_t cmd = {
        .command = "sntp",
        .help = "sntp 时间服务",
        .hint = NULL,
        .func = &cmd_sntp,
    };
    ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
}

